package gradle.common.core.context;

import java.util.*;

/**
 * 基础的上下文信息
 */
public class BaseContextHandler {

    private static ThreadLocal<Map<String, Object>> THREAD_LOCAL = new InheritableThreadLocal<>();

    /**
     * 写入值
     *
     * @param key   Key
     * @param value Value
     */
    public static void set(String key, Object value) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        map.put(key, value);
    }

    /**
     * 根据 key 获取 ThreadLocal 中的Value
     *
     * @param key Key
     * @return Value
     */
    public static Object get(String key) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            THREAD_LOCAL.set(map);
        }
        return map.get(key);
    }

    /**
     * remove value
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    /**
     * get all
     *
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public static Map<String, Object> getAll() {
        return Objects.requireNonNullElse(THREAD_LOCAL.get(), Collections.emptyMap());
    }
}
